<template>
  <div class="users">
    <BreadCrumb :breads="breads"></BreadCrumb>
    <SearchForm
      @handleSearch="handleSearch"
      @handleDialog="addDilog = true"
    ></SearchForm>
    <el-table :data="users" style="width: 100%; margin-bottom: 15px">
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column label="创建日期">
        <template slot-scope="scoped">
          {{ scoped.row.create_time | dealDate }}
        </template>
      </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="{ row }">
          <el-switch
            @change="handleChange(row)"
            v-model="row.mg_state"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleEditDialog(row)"
            circle
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDel(row.id)"
            circle
          ></el-button>
          <el-button type="success" icon="el-icon-check" circle></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSize"
      @current-change="handleNum"
      :current-page="obj.pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="obj.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <el-dialog title="添加用户" :visible.sync="addDilog" width="30%">
      <el-form
        ref="addForm"
        :model="addObj"
        :rules="addRules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addObj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addObj.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancleAdd">取 消</el-button>
        <el-button type="primary" @click="handleAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editDialog" width="30%">
      <el-form
        ref="editForm"
        :model="editObj"
        :rules="editRules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editObj.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editObj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editObj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancleEdit">取 消</el-button>
        <el-button type="primary" @click="handleEditUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getUserList,
  addUser,
  changeUserStatus,
  editUser,
  delUser,
} from "@/http/apis";
import SearchForm from "./components/SearchForm";
export default {
  components: { SearchForm },
  data() {
    const handlePassword = (rule, val, cb) => {
      cb();
    };
    return {
      breads: [
        {
          label: "首页",
          to: "Home",
        },
        {
          label: "用户管理",
          to: null,
        },
        {
          label: "用户列表",
          to: null,
        },
      ],
      obj: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      users: [],
      total: 0,
      addDilog: false,
      //添加用户的字段
      addObj: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"],
          },
          {
            validator: handlePassword,
            trigger: ["blur", "change"],
          },
        ],
        email: [],
        mobile: [],
      },
      //变基用户
      editDialog: false,
      editObj: {
        username: "",
        email: "",
        mobile: "",
      },
      editRules: {},
    };
  },
  filters: {
    //时间戳转化为年月日
    dealDate(date) {
      const val = new Date(date);
      return `${val.getFullYear()}-${
        val.getMonth() + 1 > 10
          ? val.getMonth() + 1
          : "0" + (val.getMonth() + 1)
      }-${val.getDate()}`;
    },
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const {
        data: { users, total },
      } = await getUserList(this.obj);
      this.users = users;
      this.total = total;
    },
    //每页显示条数发生变化
    handleSize(size) {
      this.obj.pagesize = size;
      this.getUserList();
    },
    //页码变化
    handleNum(num) {
      this.obj.pagenum = num;
      this.getUserList();
    },
    //搜索
    handleSearch(query) {
      this.obj = { ...this.obj, pagenum: 1, query: query };
      this.getUserList();
    },
    //添加用户
    handleAddUser() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const {
            meta: { msg },
          } = await addUser(this.addObj);
          this.$message({
            type: "success",
            message: msg,
          });
          //重置表单，防止回显上一次的数据
          this.$refs.addForm.resetFields();
          this.addDilog = false;
          this.getUserList();
        }
      });
    },
    //取消添加
    handleCancleAdd() {
      this.$refs.addForm.resetFields();
      this.addDilog = false;
    },
    //修改用户状态
    async handleChange(row) {
      row.mg_state = !row.mg_state;
      try {
        const {
          meta: { msg },
        } = await changeUserStatus({
          id: row.id,
          type: !row.mg_state,
        });
        this.$message.success(msg);
        row.mg_state = !row.mg_state;
      } catch (err) {
        return err;
      }
    },
    //编辑取消按钮事件
    handleCancleEdit() {
      this.editDialog = false;
    },
    //编辑确认按钮事件
    async handleEditUser() {
      const {
        meta: { msg },
      } = await editUser(this.editObj);
      this.$message.success(msg);
      this.getUserList();
      this.editDialog = false;
    },
    //编辑按钮弹窗显示事件
    handleEditDialog(row) {
      this.editDialog = true;
      this.editObj = JSON.parse(JSON.stringify(row));
    },
    //删除用户弹窗
    handleDel(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const {
            meta: { msg },
          } = await delUser(id);
          this.$message({
            type: "success",
            message: msg,
          });
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
  },
  mounted() {
    this.getUserList();
  },
};
</script>
<style></style>
